'use strict';

const BaseController = require('../core/base');

class RoleController extends BaseController {
  // 获取角色信息
  async roleForm() {
    const query = this.ctx.params;
    const { role } = this.ctx.service;
    const result = await role.findOne(query);
    if (result) {
      const {
        menuIds,
        perms,
        ...rest
      } = result.toObject();
      this.success(rest);
    } else {
      this.fail();
    }
  }
  // 获取角色菜单
  async roleMenus() {
    const query = this.ctx.params;
    const { role } = this.ctx.service;
    const result = await role.findOne(query);
    if (result) {
      this.success(result.menuIds);
    } else {
      this.fail();
    }
  }
  // 分页
  async list() {
    // { name }
    const query = this.ctx.request.query;
    const { role } = this.ctx.service;
    const result = await role.find(query);
    this.success(result);
  }
  // 下拉列表
  async options() {
    const { role } = this.ctx.service;
    let rootList = await role.findAll();
    rootList = rootList.map(item => ({
      label: item.name,
      value: item.id,
    }));
    this.success(rootList);
  }

  // 添加和编辑
  async save() {
    const { name } = this.ctx.request.body;
    const { id } = this.ctx.params;
    // 校验
    if (!name) return this.fail('角色名称不能为空');
    const data = this.ctx.request.body;
    const { role } = this.ctx.service;
    if (!id) {
      const result = await role.save(data);
      if (!result) {
        return this.fail('新增失败');
      }
      this.success();
    } else {
      data.id = id;
      const result = await role.save(data);
      if (!result) {
        return this.fail('更新失败');
      }
      this.success();
    }
  }
  // 修改角色菜单
  async saveRoleMenus() {
    const { id } = this.ctx.params;
    const menuIds = this.ctx.request.body;
    const { menu, role } = this.ctx.service;
    const menuList = await menu.find({ id: { $in: menuIds } });
    const perms = menuList.filter(item => item.type === 'BUTTON').map(item => item.perm);
    const data = {
      id,
      menuIds,
      perms,
    };
    const result = await role.save(data);
    if (result) {
      this.success();
    } else {
      this.fail();
    }
  }

  // 删除
  async remove() {
    let { ids } = this.ctx.params;
    ids = typeof ids === 'string' ? ids.split(',').map(v => Number(v)) : [];
    const { role } = this.ctx.service;
    let count = 0;
    if (ids.length) {
      for (const id of ids) {
        const ret = await role.remove(id);
        if (ret) count += 1;
      }
      this.success(count, `共删除${count}条数据`);
    } else {
      this.fail('参数错误');
    }
  }
}


module.exports = RoleController;
